package com.admin.service;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.admin.dao.AdminCTSDao;
import com.admin.model.ExcelReadResult;
import com.admin.model.FileMeta;
import com.admin.model.ImportExcelReprotModel;
import com.admin.util.AdminStudentExcelTool;
import com.admin.util.AdminTeacherExcelTool;
import com.common.model.AdminUser;
import com.common.model.ClassInfo;
import com.common.model.Department;
import com.common.model.StudentUser;
import com.common.model.TeacherUser;
import com.common.util.Md5Encrypt;

@Service
public class AdminCTSService {
	@Autowired
	@Qualifier("adminCTSDao")
	AdminCTSDao dao;
	/**
	 * 读取某学院下所有的班级
	 * @param clgId
	 * @param start
	 * @return
	 */
	public ArrayList<ClassInfo> getClassesByClgId(int clgId,int page){
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		return dao.getClassesByClgId(clgId, start);
	}
	/**
	 * 通过班级id获取班级
	 * @param classId
	 * @return
	 */
	public ClassInfo getClassByClassId(int classId){
		return dao.getClassByClassId(classId);
	}
	/**
	 *通过班级no获取班级
	 * @param classNo
	 * @return
	 */
	public ClassInfo getClassByClassNo(String classNo){
		return dao.getClassByClassNo(classNo);
	}
	/**
	 * 通过班级name获取班级
	 * @param className
	 * @return
	 */
	public ClassInfo getClassByClassName(String className){
		return dao.getClassByClassName(className);
	}
	/**
	 * 读取某学院下所有班级数目
	 * @param clgId
	 * @return
	 */
	public int getClassesCountByClgId(int clgId){
		return dao.getClassesCountByClgId(clgId);
	}
	/**
	 * 添加一个班级
	 * @param classinfo
	 * @return -1 重复no -2  重复name -3参数错误
	 */
	public int insertClass(ClassInfo classinfo){
		if(dao.getClassCountByClassNo(classinfo.getNo())>0){
			return -1;
		}
		if(dao.getClassCountByClassName(classinfo.getName())>0){
			return -2;
		}
		try{
			dao.insertClass(classinfo);
		}catch(Exception e){
			return -3;
		}
		return 0;
	}
	/**
	 * 修改一个班级
	 * @param classinfo
	 * @return
	 */
	public int updateClass(ClassInfo classinfo){
		dao.updateClass(classinfo);
		return 0;
	}
	/**
	 * 删除一个班级
	 * @param classId
	 * @return -1 还有学生存在
	 */
	public int deleteClass(int classId){
		if(dao.getStudentsCountByClassId(classId)>0){
			return -1;
		}
		dao.deleteClass(classId);
		return 0;
	}
	public int insertClassBulk(ClassInfo classinfo,int count){
		long noStart=0;
		int nameNoStart=1;
		try {
			noStart=Long.parseLong(classinfo.getNo());
		} catch (NumberFormatException  e) {
			noStart=1;
		}
		//班级名中有无x(占位符)
		boolean hasX=classinfo.getName().indexOf("x")==-1?false:true;
		for(int i=1;i<count+1;i++){
			ClassInfo c=new ClassInfo();
			c.setProf_id(classinfo.getProf_id());
			while(dao.getClassCountByClassName(nameNoStart+"")>0){
				nameNoStart++;
			}
			if(hasX){
				c.setName(classinfo.getName().replaceAll("x",nameNoStart+""));
			}else{
				c.setName(classinfo.getName()+nameNoStart);
			}
			while(dao.getClassCountByClassNo(noStart+"")>0){
				noStart++;
			}
			c.setNo(noStart+"");
			noStart++;
			nameNoStart++;
			dao.insertClass(c);
		}
		return 0;
	}
	/**
	 * 通过系获取下面的所有班级
	 * @param depId
	 * @return
	 */
	public ArrayList<ClassInfo> getClassesByDepId(int depId){
		if(depId==0){
			return new ArrayList<ClassInfo>();
		}
		return dao.getClassesByDepId(depId);
	}
	/**
	 * 获取某系下面最小的班级id 
	 * @param depId
	 * @return
	 */
	public int getMinClassIdOfDepartment(int depId){
		if(depId==0){
			return 0;
		}
		return dao.getMinClassIdOfDepartment(depId);
	}
	/**
	 * 获取某学院下面最小的班级id
	 * @param clgId
	 * @return
	 */
	public ClassInfo getMinClassOfCollege(int clgId){
		return dao.getMinClassOfCollege(clgId);
	}
	/**
	 * 获取最小的班级id
	 * @return
	 */
	public ClassInfo getMinClass(){
		return dao.getMinClass();
	}
	/**
	 * 分页查询某班级下所有学生
	 * @param classId
	 * @param start
	 * @return
	 */
	public ArrayList<StudentUser>getStudentsByClassId(int classId,int page){
		if(classId==0){
			return new ArrayList<StudentUser>();
		}
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		return dao.getStudentsByClassId(classId, start);
	}
	/**
	 * 根据学生id查询学生
	 * @param stuId
	 * @return
	 */
	public StudentUser getStudentByStuId(int stuId){
		if(stuId==0){
			return new StudentUser();
		}
		return dao.getStudentByStuId(stuId);
	}
	/**
	 * 根据学生no查询学生
	 * @param stuNo
	 * @return
	 */
	public StudentUser getStudentByStuNo(String stuNo){
		return dao.getStudentByStuNo(stuNo);
	}
	/**
	 * 获取某班级的学生人数
	 * @param classId
	 * @return
	 */
	public int getStudentsCountByClassId(int classId){
		return dao.getStudentsCountByClassId(classId);
	}
	/**
	 * 学生插入校验
	 * @param student
	 * @return
	 */
	public boolean insertCheck(StudentUser student){
		if(student.getNo()==null||student.getNo().trim().isEmpty()||student.getClass_id()==null){
			return false;
		}
		if(student.getGender()==null||student.getGender().trim().isEmpty()){
			return false;
		}
		if(student.getGrade()==null||student.getGrade().trim().isEmpty()){
			return false;
		}
		if(student.getName()==null||student.getName().trim().isEmpty()){
			return false;
		}
		if(student.getPassword()==null||student.getPassword().trim().isEmpty()){
			return false;
		}
		return true;
	}
	public boolean updateCheck(StudentUser student){
		if(student.getId()==null||student.getNo()==null||student.getNo().trim().isEmpty()||student.getClass_id()==null){
			return false;
		}
		if(student.getGender()==null||student.getGender().trim().isEmpty()){
			return false;
		}
		if(student.getGrade()==null||student.getGrade().trim().isEmpty()){
			return false;
		}
		if(student.getName()==null||student.getName().trim().isEmpty()){
			return false;
		}
		return true;
	}
	/**
	 * 格式化学生数据
	 * @param student
	 * @return
	 */
	public StudentUser formatStudent(StudentUser student){
		student.setNo(student.getNo().trim());
		if(student.getGender().indexOf("男")!=-1){
			student.setGender("男");
		}else{
			student.setGender("女");
		}
		student.setName(student.getName().trim());
		student.setGrade(student.getGrade().trim());
		if(student.getPassword()!=null){
			student.setPassword(Md5Encrypt.encrypt(student.getPassword().trim()));
		}
		return student;
	}
	/**
	 * 增加一个学生
	 * @param student
	 * @return -1 参数错误 -2重复no -3参数错误2
	 */
	public int insertStudent(StudentUser student){
		if(!insertCheck(student)){
			return -1;
		}
		if(dao.getStudentByStuNo(student.getNo())!=null){
			return -2;
		}
		try {
			dao.insertStudent(formatStudent(student));
		} catch (Exception e) {
			return -3;
		}
		return 0;
	}
	/**
	 * 修改一个学生
	 * @param student
	 * @return -1参数错误 -2 重复no,-3参数错误2
	 */
	public int updateStudent(StudentUser student){
		if(!updateCheck(student)){
			return -1;
		}
		StudentUser stuCheck=dao.getStudentByStuNo(student.getNo());
		if(stuCheck!=null&&stuCheck.getId()!=student.getId()){
			return -2;
		}
		try {
			dao.updateStudent(formatStudent(student));
		} catch (Exception e) {
			return -3;
		}
		return 0;
	}
	/**
	 * 重置学生密码
	 * @param password
	 * @param stuId
	 * @return -1 参数错误
	 */
	public int resetStudentPassword(String password,int stuId){
		if(password==null|password.trim().isEmpty()){
			return -1;
		}
		password=Md5Encrypt.encrypt(password);
		dao.resetStudentPassword(password, stuId);
		return 0;
	}
	/**
	 * 删除一个学生
	 * @param stuId
	 * @return -1有意向题目 -2已选择毕业设计题目
	 */
	public int deleteStudent(int stuId){
		/*if(dao.getIntentProjectCountOfStudent(stuId)>0){
			return -1;
		}*/
		if(dao.getProjectCountOfStudent(stuId)>0){
			return -2;
		}
		dao.deleteStudent(stuId);
		return 0;
	}
	public int insertStudentByExcel(FileMeta excel,HttpSession session){
		AdminStudentExcelTool studentExcelTool=new AdminStudentExcelTool();
		ExcelReadResult<ImportExcelReprotModel<StudentUser>> result= studentExcelTool.readExcel(excel);
		ExcelReadResult<ImportExcelReprotModel<StudentUser>> error= new ExcelReadResult<>();
		error.setErrorMsg(result.getErrorMsg());
		error.setTotalDataCount(result.getTotalDataCount());
		AdminUser admin=(AdminUser) session.getAttribute("user");
		//致命错误,不导入数据库
		if(result.getErrorMsg()!=null){
			session.setAttribute("studentExcelReadResult", error);
			session.setAttribute("studentExcelReadSuccessCount", 0);
			return 0;
		}
		ArrayList<ImportExcelReprotModel<StudentUser>> dataList=result.getDataList();
		int dataSize=dataList.size();
		int successCount=0;
		//循环导入数据库
		for(int i=0;i<dataSize;i++){
			ImportExcelReprotModel<StudentUser> report=dataList.get(i);
			if(report.errorMsg!=null){
				error.getDataList().add(report);
				report.setErrorLine(i+2);
				continue;//此项数据有错,则这一项就不导入数据库
			}
			StudentUser stu=report.getData();;
			//检查是否重复no
			if(dao.getStudentByStuNo(stu.getNo())!=null){
				report.setErrorMsg("已经存在学号为:"+stu.getNo()+"的学生");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			ClassInfo classinfo=dao.getClassByClassName(stu.getClassInfo().getName());
			if(classinfo==null){
				report.setErrorMsg("班级 "+stu.getClassInfo().getName()+" 不存在");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			if(!admin.isSuperAdmin()&&admin.getCollegeId()!=classinfo.getBranch().getProf().getDepartment().getCollege().getId()){
				report.setErrorMsg("班级 "+stu.getClassInfo().getName()+" 不属于您的学院,不能添加");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			stu.setClass_id(classinfo.getId());
			try{
				dao.insertStudent(stu);
			}catch(Exception e){
				e.printStackTrace();
				report.setErrorMsg("参数错误,请检查");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			successCount++;
		}
		session.setAttribute("studentExcelReadResult", error);
		session.setAttribute("studentExcelReadSuccessCount", successCount);
		return 0;
	}
	/**
	 * 通过系读取教师
	 * @param depId
	 * @param page
	 * @return
	 */
	public ArrayList<TeacherUser> getTeachersByDepId(int depId,int page){
		if(depId==0){
			return new ArrayList<TeacherUser>();
		}
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		return dao.getTeachersByDepId(depId, start);
	}
	/**
	 * 通过教师id获取教师
	 * @param teaId
	 * @return
	 */
	public TeacherUser getTeacherByTeacherId(int teaId){
		return  dao.getTeacherByTeacherId(teaId);
	}
	/**
	 * 通过教师no获取教师
	 * @param teaNo
	 * @return
	 */
	public TeacherUser getTeacherByTeacherNo(String teaNo){
		return dao.getTeacherByTeacherNo(teaNo);
	}
	/**
	 * 修改校验教师
	 * @param teacher
	 * @return
	 */
	public boolean insertTeacherCheck(TeacherUser teacher){
		if(teacher.getNo()==null||teacher.getNo().trim().isEmpty()||teacher.getDepartmentId()==null){
			return false;
		}
		if(teacher.getGender()==null||teacher.getGender().trim().isEmpty()){
			return false;
		}
		if(teacher.getName()==null||teacher.getName().trim().isEmpty()){
			return false;
		}
		if(teacher.getPassword()==null||teacher.getPassword().trim().isEmpty()){
			return false;
		}
		return true;
	}
	/**
	 * 修改校验教师
	 * @param teacher
	 * @return
	 */
	public boolean updateTeacherCheck(TeacherUser teacher){
		if(teacher.getId()==null||teacher.getNo()==null||teacher.getNo().trim().isEmpty()||teacher.getDepartmentId()==null){
			return false;
		}
		if(teacher.getGender()==null||teacher.getGender().trim().isEmpty()){
			return false;
		}
		if(teacher.getName()==null||teacher.getName().trim().isEmpty()){
			return false;
		}
		return true;
	}
	/**
	 * 格式化学生数据
	 * @param student
	 * @return
	 */
	public TeacherUser formatTeacher(TeacherUser teacher){
		teacher.setNo(teacher.getNo().trim());
		if(teacher.getGender().indexOf("男")!=-1){
			teacher.setGender("男");
		}else{
			teacher.setGender("女");
		}
		teacher.setName(teacher.getName().trim());
		if(teacher.getPassword()!=null){
			teacher.setPassword(Md5Encrypt.encrypt(teacher.getPassword().trim()));
		}
		return teacher;
	}
	/**
	 * 修改教师
	 * @param teacher
	 * @return -1参数错误 -2 重复no,-3参数错误2
	 */
	public int updateTeacher(TeacherUser teacher){
		if(!updateTeacherCheck(teacher)){
			return -1;
		}
		TeacherUser teaCheck=dao.getTeacherByTeacherNo(teacher.getNo());
		if(teaCheck!=null&&teaCheck.getId()!=teacher.getId()){
			return -2;
		}
		try {
			dao.updateTeacher(formatTeacher(teacher));
		} catch (Exception e) {
			e.printStackTrace();
			return -3;
		}
		return 0;
	}	
	/**
	 * 增加一个教师
	 * @param teacher
	 * @return -1 参数错误 -2重复no -3参数错误2
	 */
	public int insertTeacher(TeacherUser teacher){
		if(!insertTeacherCheck(teacher)){
			return -1;
		}
		if(dao.getTeacherByTeacherNo(teacher.getNo())!=null){
			return -2;
		}
		try {
			dao.insertTeacher(formatTeacher(teacher));
		} catch (Exception e) {
			return -3;
		}
		return 0;
	}
	/**
	 * 重置学生密码
	 * @param password
	 * @param teaId
	 * @return -1 参数错误
	 */
	public int resetTeacherPassword(String password,int teaId){
		if(password==null|password.trim().isEmpty()){
			return -1;
		}
		password=Md5Encrypt.encrypt(password);
		dao.resetTeacherPassword(password, teaId);
		return 0;
	}
	/**
	 * 删除一个学生
	 * @param stuId
	 * @return -1有毕业设计
	 */
	public int deleteTeacher(int teaId){
		if(dao.getProjectCountOfTeacher(teaId)>0){
			return -1;
		}
		dao.deleteTeacher(teaId);
		return 0;
	}
	public int insertTeacherByExcel(FileMeta excel,HttpSession session){
		AdminTeacherExcelTool teacherExcelTool=new AdminTeacherExcelTool();
		ExcelReadResult<ImportExcelReprotModel<TeacherUser>> result= teacherExcelTool.readExcel(excel);
		ExcelReadResult<ImportExcelReprotModel<TeacherUser>> error= new ExcelReadResult<>();
		error.setErrorMsg(result.getErrorMsg());
		error.setTotalDataCount(result.getTotalDataCount());
		AdminUser admin=(AdminUser) session.getAttribute("user");
		//致命错误,不导入数据库
		if(result.getErrorMsg()!=null){
			session.setAttribute("teacherExcelReadResult", error);
			session.setAttribute("teacherExcelReadSuccessCount", 0);
			return 0;
		}
		ArrayList<ImportExcelReprotModel<TeacherUser>> dataList=result.getDataList();
		int dataSize=dataList.size();
		int successCount=0;
		//循环导入数据库
		for(int i=0;i<dataSize;i++){
			ImportExcelReprotModel<TeacherUser> report=dataList.get(i);
			if(report.errorMsg!=null){
				error.getDataList().add(report);
				report.setErrorLine(i+2);
				continue;//此项数据有错,则这一项就不导入数据库
			}
			TeacherUser teacher=report.getData();
			//检查是否重复no
			if(dao.getTeacherByTeacherNo(teacher.getNo())!=null){
				report.setErrorMsg("已经存在工号为:"+teacher.getNo()+"的教师");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			Department department=dao.getDepartmentByDepName(teacher.getDepartment().getName());
			if(department==null){
				report.setErrorMsg("系 "+teacher.getDepartment().getName()+" 不存在");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			if(!admin.isSuperAdmin()&&admin.getCollegeId()!=department.getCollege().getId()){
				report.setErrorMsg("系 "+teacher.getDepartment().getName()+" 不属于您的学院,不能添加");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			teacher.setDepartmentId(department.getId());
			try{
				dao.insertTeacher(teacher);
			}catch(Exception e){
				e.printStackTrace();
				report.setErrorMsg("参数错误,请检查");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			successCount++;
		}
		session.setAttribute("teacherExcelReadResult", error);
		session.setAttribute("teacherExcelReadSuccessCount", successCount);
		return 0;
	}
	/**
	 * 查询指定系下所有的教师
	 * @param depId
	 * @return
	 */
	public ArrayList<TeacherUser> getAllTeacherOfDep(int depId){
		return dao.getAllTeacherOfDep(depId);
	}
}
